import { reactive, ref, watch, computed } from "vue";
import { queryArticleInfo, handleArticleStatus } from "../../service/article/"
import jsCookie from "js-cookie"
import { zlDialog } from "../../utils/zlDialog";
import { matchingPolicyByID } from "../../service/matching";
import { getProjectRes } from "../../service/article/";
import { useUserStore } from "../../store/user"
import { useRoute } from "vue-router"

export const useDetailHooks = () => {
  // document.addEventListener('contextmenu', function (e) {
  //   alert("禁止复制")
  //   e.preventDefault();
  // });

  // document.addEventListener('keydown', function (e) {
  //   if ((e.ctrlKey || e.metaKey) && (e.key === 'c' || e.key === 'C')) {
  //     alert("禁止复制")

  //     // 阻止Ctrl+C或Command+C的默认行为
  //     e.preventDefault();
  //   }
  // });

  const userStore = useUserStore()
  const route: any = useRoute()
  const activeName = ref('first')

  const auth = computed<any>(() => userStore.auth)
  const userInfo = computed<any>(() => userStore.userInfo)


  const detailPageLoading = ref(true)

  interface DetailInfoType {
    id: any,
    searchType: any,
    isLike: any,
    isCollect: any,
    collectNum: any,
    likeNum: any,
    attachments: string,
    articleOrigin: string,
    proof: string,
    orgName: string,
    createName: string,
    character: string,
    publishDate: string,
    completeDate: string,
    itemData: any[],
    itemType:String,
    name:String
  }
  const detailInfo = reactive<DetailInfoType>({
    id: "",
    searchType: "1",
    isLike: 0,
    isCollect: 0,
    collectNum: 0,
    likeNum: 0,
    attachments: "",
    articleOrigin: "",
    proof: "",
    createName: "",
    character: "",
    publishDate: "",
    completeDate: "",
    orgName: "",
    itemData: [],
    itemType:'',
    name:''
  });

  const info = ref<any>()

  const url = new URL(location.href);


  const searchParams = url.searchParams;

  //监听路由query变化
  watch(
    () => searchParams,
    (newVal) => {
      detailInfo.id = newVal.get("id");
      detailInfo.searchType = newVal.get("searchType");
      detailInfo.name = newVal.get('name');
    },
    { deep: true, immediate: true }
  );

  // 发送网络请求请求页面详情
  console.log(detailInfo)

  queryArticleInfo({ ...detailInfo }).then((res: any) => {
    info.value = res?.data
    const {
      content,
      title,
      isLike,
      isCollect,
      collectNum,
      likeNum,
      proof,
      orgName,
      createName,
      character,
      publishDate,
      completeDate,
      itemData,
      existPolicy,
      itemType,
      name
    } = res?.data || {}
    details.value = content
    pageTitle.value = title
    detailInfo.collectNum = collectNum
    detailInfo.likeNum = likeNum
    detailInfo.proof = proof
    detailInfo.orgName = orgName
    detailInfo.createName = createName
    detailInfo.character = character
    detailInfo.publishDate = publishDate
    detailInfo.completeDate = completeDate
    detailInfo.itemData = itemData
    detailInfo.existPolicy = existPolicy
    detailInfo.itemType = itemType
    detailInfo.name = name
    functionBtns.value[0].isActive = !!(isLike * 1)
    functionBtns.value[1].isActive = !!(isCollect * 1)
    functionBtns.value[0].counter = likeNum
    functionBtns.value[1].counter = collectNum
    functionBtns.value[0].icon = !(isLike * 1)
      ? new URL(`../../assets/image/love_default.png`, import.meta.url)
      : new URL(`../../assets/image/love_active.png`, import.meta.url);
    functionBtns.value[1].icon = !(isCollect * 1)
      ? new URL(`../../assets/image/favorite_default.png`, import.meta.url)
      : new URL(`../../assets/image/favorite_active.png`, import.meta.url);
  }).finally(() => {
    detailPageLoading.value = false
  })

  // 发送网络请求请求政策图谱
  const policyData = ref<any>(null)
  if (detailInfo.searchType == 1) {
    matchingPolicyByID(detailInfo.id).then((res: any) => {
      policyData.value = { id: "0", label: "关联政策", children: [...res.data] };
    })
  }


  const pageTitle = ref("")
  const details = ref("");
  const editorOption = {};

  /**
   * 点赞\收藏\分享
   */
  const functionBtns = ref([
    {
      type: "like",
      icon: new URL("@/assets/image/love_default.png", import.meta.url),
      counter: 0,
      isActive: false
    },
    {
      type: "favorite",
      icon: new URL("@/assets/image/favorite_default.png", import.meta.url),
      counter: 0,
      isActive: false
    }
  ]);

  const handleIconClick = (idx: number) => {
    if (idx == 2) return false;
    if (!jsCookie.get("token")) {
      return zlDialog()
    }
    let handleType: "1" | "2" = "1"
    let curType = "";
    switch (idx) {
      case 0:
        curType = "love";
        handleType = "1"
        break;
      case 1:
        curType = "favorite";
        handleType = "2"
        break;
      case 2:
        curType = "promotion";
        break;
    }

    handleArticleStatus({ sourceId: detailInfo.id, sourceType: detailInfo.searchType, type: handleType })

    functionBtns.value[idx].isActive ? functionBtns.value[idx].counter-- : functionBtns.value[idx].counter++
    functionBtns.value[idx].isActive = !functionBtns.value[idx].isActive;
    functionBtns.value[idx].icon = !functionBtns.value[idx].isActive
      ? new URL(`../../assets/image/${curType}_default.png`, import.meta.url)
      : new URL(`../../assets/image/${curType}_active.png`, import.meta.url);
  };

  // 分享
  type ShareType = "wb" | "qq";
  const handleShareClick = (type: ShareType) => {
    let url = "";
    let shareUrl = window.location.href;
    switch (type) {
      case "wb":
        url = `http://service.weibo.com/share/share.php?title=${pageTitle.value}&url=${shareUrl}`;
        break;
      case "qq":
        url = `https://connect.qq.com/widget/shareqq/index.html?title=${pageTitle.value}&url=${shareUrl}`;
        break;
    }

    window.open(url, "_blank");
  };

  /**
   * 动画逻辑
   */
  const playAnimate = (e: any) => {
    e.target.classList.add("pulse");
  };

  const stopAnimate = (e: any) => {
    e.target.classList.remove("pulse");
  };

  // 下载附件
  const downloadDoc = (url: string) => {
    window.open(`https://api.touce.com.cn${url}`, "_blank");
  }

  // 政策跳转
  const goDetailPage = (id: string, searchType: any) => {
    window.open(`${location.origin}/detail?id=${id}&searchType=${searchType}`, "_blank")
  }

  // 获取政策接口
  const projectLoading = ref(false)
  const projectQueryInfo = reactive({
    pageNum: 1,
    pageSize: 10,
  })
  const projectList = ref<any[]>([])
  const projectTotal = ref<number>(0)
  const getProjectList = async () => {
    projectLoading.value = true
    const res = await getProjectRes({ ...projectQueryInfo, id: detailInfo.id })
    projectList.value = res.rows
    projectTotal.value = res.total
    projectLoading.value = false
  }

  const pageInfoChange = () => {
    getProjectList()
  }

  getProjectList()

  return {
    detailInfo,
    details,
    pageTitle,
    editorOption,
    playAnimate,
    stopAnimate,
    functionBtns,
    handleIconClick,
    handleShareClick,
    downloadDoc,
    policyData,
    goDetailPage,
    getProjectList,
    projectList,
    projectTotal,
    pageInfoChange,
    projectQueryInfo,
    projectLoading,
    info,
    detailPageLoading,
    auth,
    userInfo,
    activeName
  };
};
